import React, { useMemo } from 'react';
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { getUserInfo, isLoggedIn } from '@/utils/auth';
import { ROUTE_PERMISSION_MAP, MENU_PERMISSION_CODES } from '@/config/menuPermissions';

/**
 * 受保护的路由组件
 * 用于验证用户是否已登录，如果未登录则重定向到登录页
 */
const ProtectedRoute: React.FC = () => {
  const location = useLocation();
  const loggedIn = isLoggedIn();
  const userInfo = loggedIn ? getUserInfo() : null;
  const permissions = useMemo(() => {
    const list = userInfo?.permissions;
    if (!Array.isArray(list)) {
      return [];
    }
    return list;
  }, [userInfo?.permissions]);
  // 当权限包含 '*'、为空（后端未返回）默认放行
  // 另外：如果后端返回的权限与本系统的菜单权限编码没有任何交集，则视为“未启用细粒度菜单权限”，默认放行
  const allMenuCodes: string[] = Object.values(MENU_PERMISSION_CODES);
  const hasMappedPermission = permissions.some((p: string) => allMenuCodes.includes(p));
  const hasAllAccess =
    permissions.includes('*') ||
    permissions.length === 0 ||
    !hasMappedPermission ||
    userInfo?.roleKey === 'super-admin';

  const firstAccessiblePath = useMemo(() => {
    if (hasAllAccess) return '/dashboard';
    for (const [path, permission] of Object.entries(ROUTE_PERMISSION_MAP)) {
      if (!permission || permissions.includes(permission)) {
        return `/${path}`;
      }
    }
    return null;
  }, [hasAllAccess, permissions]);

  if (!loggedIn) {
    return <Navigate to="/login" replace />;
  }

  const pathKey = location.pathname.replace(/^\//, '') || 'dashboard';
  const requiredPermission = ROUTE_PERMISSION_MAP[pathKey];

  if (!hasAllAccess && requiredPermission && !permissions.includes(requiredPermission)) {
    if (firstAccessiblePath) {
      return <Navigate to={firstAccessiblePath} replace />;
    }
    // 无任何可访问页面
    return <Navigate to="/login" replace />;
  }

  const roleKey = (userInfo?.roleKey || userInfo?.roleName || '').toLowerCase();
  if (pathKey === 'user' && roleKey !== 'super-admin') {
    if (firstAccessiblePath) {
      return <Navigate to={firstAccessiblePath} replace />;
    }
    return <Navigate to="/dashboard" replace />;
  }

  return <Outlet />;
};

export default ProtectedRoute;